#coding=utf-8
from iLibP.loger import LogInfo
from models import s_no

__author__ = 'jy@cjlu.edu.cn'

#=======================================================================================================================
#功能编号:[0012]
#功能名称:银行信息管理
#功能:主要用于管理集团资金涉及的各个银行的基础信息
#=======================================================================================================================
from iLibP.loger import *
from basehandler import basehandler
from config import *
from SysCommon.exceloperator import ExcelOperator
from SysCommon.tools import *
from models.d_bankinfo import *
import json

def SqlWhereStr(i):
    """
    专门用于生成where条件,根据实际情况修改
    """
    fields=[
	"bankno",
		"bankname",
	]
    i=InitStorageBlank(i,fields)
    strwhere=" id>0 "
    if i.bankno:
        strwhere+=" and bankno='"+safewhere(i.bankno)+"'"
    if i.bankname:
        strwhere+=" and bankname like '%"+safewhere(i.bankname)+"%'"
    return strwhere

def DataFilter(i):
    obj=bll_d_bankinfo()
    i.pageindex=i.get("pageindex",0)            #指定默认值
    i.pagesize=i.get("pagesize",13)             #指定默认值
    i.rc=0
    i.pc=0
    i.recs=[]
    #补充其他查询条件
    strwhere=SqlWhereStr(i)
    i.recs,i.rc,i.pc=obj.GetPagedRowsByDbWhere(i.pageindex,i.pagesize,where=strwhere)
    i.recs=i.recs.list()
    return i

class Ajax(basehandler):
    def get(self):
        self.set_header("Content-Type", "text/html; charset=UTF-8")
        i=self.input()
        cmd=i.get("act","")
        if cmd=="ajax1":               #用于查询数据
            i=DataFilter(i)
            t=global_lookup.get_template("f00/T/TT/f0012_ajax1.html")
            self.write(t.render(i=i))
    def post(self):
        cu=self.get_currentuser()
        self.set_header("Content-Type", "application/json; charset=UTF-8")
        i=self.input()
        cmd=i.get("act","")
        obj=bll_d_bankinfo()
        if cmd=="del":
            if i.id:
                obj.DelRowById(i.id)
                self.write(json.dumps({"result":"OK"}))
        if  cmd=="add":
            try:
                i.id=0
                i.bankno=s_no.GC_COUNT("BANKNO",4,False)
                obj.Save(i)
                self.write(json.dumps({"result":"OK"}))
            except:
                self.write(json.dumps({"result":"NOOK"}))
        if cmd=="edit":
            obj.Save(i)
            return json.dumps({"result":"OK"})
        if cmd=="off":
            if i.id:
                self.get_currentuser()
                tobj=obj.GetRowById(i.id)
                obj.UpdateColValue(i.id,"bankstatus","N")
                LogInfo("%s修订银行[%s]状态信息到无效"%(cu.truename,tobj.bankname))
                self.write(json.dumps({"result":"OK"}))
        if cmd=="on":
            if i.id:
                tobj=obj.GetRowById(i.id)
                obj.UpdateColValue(i.id,"bankstatus","Y")
                LogInfo("%s修订银行[%s]状态信息到无效"%(cu.truename,tobj.bankname))
                self.write(json.dumps({"result":"OK"}))


class List(basehandler):
    """
    用于处理列表页面或默认显示页面
    对于数据的删除或简单AJAX的操作也放置在此类中，
    可放置于post函数内
    """
    def get(self):
        self.set_header("Content-Type", "text/html; charset=UTF-8")
        i=self.input()
        cmd=i.get("act","list")
        if cmd=="list":
            t=global_lookup.get_template("f00/T/f0012_list.html")
            i=DataFilter(i)
            self.write(t.render(i=i))
        if cmd=="update":
            obj=bll_d_bankinfo()
            t=global_lookup.get_template("f00/T/f0012_update.html")
            if i.get("id",None):
                i.rec=obj.GetRowById(i.id)

            self.write(t.render(i=i))
    def post(self):
        self.set_header("Content-Type", "text/html; charset=UTF-8")
        i=self.input()
        cmd=i.get("act","list")
        if cmd=="search":
            t=global_lookup.get_template("f00/T/f0012_list.html")
            i=DataFilter(i)
            self.write(t.render(i=i))

class Import(basehandler):
    def get(self):
        self.set_header("Content-Type", "text/html; charset=UTF-8")
        i=self.input()
        #请修改路径
        t=global_lookup.get_template("f00/T/f0012_import.html")
        self.write(t.render())
    def post(self):
        self.set_header("Content-Type", "text/html; charset=UTF-8")
        optobj=bll_d_bankinfo()
        #1.导入数据时只做更新操作，特别注意不能删除数据
        t=optobj.Transaction()
        eo=ExcelOperator()                          #file控件名要为excel
        f=eo.uploadFile()
        result=eo.parseExcel(f)
        importresult=[]
        try:
            for d in result.data:
                #查找部分数据
                try:
                    #修改查询条件
                    strwhere="employeeno='"+d.employeeno+"'"
                    rec=optobj.GetRowByStrWhere(strwhere)
                    if rec:#找到更新
                        d=CopyData(rec,d)
                        #补充需要更新的列名
                        optobj.SaveEx(d,["id",""])
                        d.importstatus=u"【成功】更新"
                    else:#找不到则写入
                        d.id=0
                        optobj.Save(d)
                        d.importstatus=u"【成功】写入"
                except Exception,ex1:
                    print ex1
                    d.importstatus=u"【失败】数据异常"
                importresult.append(d)
            optobj.Commit(t)
            t=global_lookup.get_template("f00/T/f0012_importresult.html")
            self.write(t.render(datas=importresult))
        except Exception,ex:
            msg=u"iLib执行Save函数出错,[具体信息]:"+str(ex)
            LogError(msg)
            optobj.RollBack(t)
            raise Exception,msg

class Export(basehandler):
    """
    用于将数据导出向EXCEL
    """
    def post(self):
        self.set_header("Content-Type", "application/json; charset=UTF-8")
        i=self.input()
        from SysCommon.exceloperator import ExcelOperator
        excelobj=ExcelOperator()
        wb,ws=excelobj.openExistExcel(TP_PATH+"/static/T/f0012.xls")
        start_row=3
        #1.获取数据
        bjobj=bll_d_bankinfo()
        strwhere=SqlWhereStr(i)
        datas=bjobj.GetRowsByStrWhere(strwhere)
        #2.组合excel
        for d in datas:
            ws.write(start_row,0,d.bankno)
            ws.write(start_row,1,d.bankname)
            ws.write(start_row,2,d.addressdetail)
            ws.write(start_row,3,d.accountno)
            ws.write(start_row,4,d.customermanager)
            ws.write(start_row,5,d.managerphoneno)
            ws.write(start_row,6,d.bz)
            start_row+=1
            #3.输出excel
        nfilename="/static/tmpfiles/f0012_"+TimeStr()+".xls"
        wb.save(TP_PATH+nfilename)
        self.write(JsonResult(nfilename))